<template>
  <!-- 控制阀 -->
  <view class="container setMarginTop">
    <uni-section title="手动控制阀门" type="line">
      <view class="example-body">
        <view class="result-box">
          <text>所选阀门：</text>
        </view>
        <uni-combox :candidates="candidates" placeholder="请选择要要操作的阀门" v-model="city" class="combox"></uni-combox>
      </view>
    </uni-section>
  </view>

  <view class=" setMarginBottom">
    <view class="uni-padding-wrap uni-common-mt">
      <view class="button-sp-area">
        <button class="mini-btn" @click="closeValve" type="primary" size="mini">关闭阀门</button>
        <!-- <button class="mini-btn" type="default" size="mini">按钮</button> -->
        <button class="mini-btn" @click="openValve" type="warn" size="mini">开启阀门</button>
      </view>
    </view>
  </view>

  <view class="container">
    <uni-section title="扫码控制阀" type="line">
    </uni-section>
  </view>
  <view class="page-body">
    <!-- 扫码控制阀 -->
    <view class="btn-area" id="buttonContainer">
      <view class="button-sp-area">
        <button class="close-valve" type="primary" @click="doScanCodeClose">扫码关阀</button>
        <button type="warn" @click="doScanCodeOpen">扫码开阀</button>
      </view>
      <view class="setMarginTop">
        <view v-if="getQRcodeDataClose">{{ getQRcodeDataClose }} <span class="text">已关闭</span></view>
        <view v-if="getQRcodeDataOpen">{{ getQRcodeDataOpen }} <span class="text">已打开</span></view>
        <view v-for="item in chainValveList" :key="item.id">
          <view v-if="item"><span class="text">{{ item.valvePositionNumber }} 联锁阀门已开</span>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { http } from '@/utils/http';
import type ScanCodeReturnData from '@/types/scanCodeReturnData';
import type ValveOperationResult from '@/types/ValveOperationResult';
import type Valves from '@/types/valves';
import { useValvesStore } from '@/stores/modules/getValvesData';

const valvesStore = useValvesStore();

const getQRcodeDataClose = ref<string | null>(null);
const getQRcodeDataOpen = ref<string | null>(null);
const userName = uni.getStorageSync('rememberedUsername');
const candidates = ref<string[]>([]);
const city = ref('');

const chainValveList = ref<Valves[]>([]);

candidates.value = valvesStore.valvesList;

//判断所选阀门是否在候选项中
/* const judge = () => {
  // 定义需要验证的 city 字段
  const citiesToValidate = [city];

  // 遍历每个 city 字段，检查其值是否在 candidates 中
  for (const c of citiesToValidate) {
    if (c.value && !candidates.value.includes(c.value)) {
      uni.showToast({
        title: '所选任务阀门包含无效选项，请重新选择',
        icon: 'none',
        duration: 2000
      });
      return false; // 如果有任何一个城市不是有效的候选选项，则停止提交
    }
  }
} */

// 手动关闭阀门
const closeValve = async () => {
  getQRcodeDataClose.value = null;
  getQRcodeDataOpen.value = null;
  //判断数据的数据是否在候选项中
  /*   if (judge()) {
      return;
    } */

  try {
    //关闭阀门
    const result = await operationValve(city.value, 0, userName);

    //关闭联锁提醒显示
    chainValveList.value = [];
    //如果状态更新成功，则显示关闭成功提醒
    if (result.statusUpdateFlag === 1) {
      getQRcodeDataClose.value = city.value;
      getQRcodeDataOpen.value = null
    }

    //乳沟如果记录成功、阀门状态更新成功，则执行成功提醒
    if (result.recordFlag === 1 && result.statusUpdateFlag === 1) {
      uni.showToast({
        title: '关闭成功！',
        icon: 'success',
        duration: 2000,
      });
    } else {
      uni.showToast({
        title: '关闭失败！',
        icon: 'error',
        duration: 2000,
      });
    }
  } catch (error) {
    console.error('关闭阀门时出错:', error);
    uni.showToast({
      title: '关闭失败！！',
      icon: 'error',
      duration: 2000,
    });
  }



  /*   result.then(v => {
      if (v === 2) {
        uni.showToast({
          title: '关闭成功！',
          icon: 'success',
          duration: 2000,
        });
        getQRcodeDataClose.value = city.value;
        getQRcodeDataOpen.value = null
      } else {
        uni.showToast({
          title: '关闭失败！！',
          icon: 'error',
          duration: 2000,
        });
      }
  
    }) */

};

// 手动打开阀门
const openValve = async () => {
  getQRcodeDataOpen.value = null;
  getQRcodeDataClose.value = null;
  try {
    // 打开阀门（执行）
    const result = await operationValve(city.value, 1, userName);
    console.log('关闭阀门:', result);
    console.log('关闭阀门recordFlag):', result.recordFlag);
    console.log('关闭阀门statusUpdateFlag:', result.statusUpdateFlag);
    console.log('关闭阀门valveList:', result.valveList);

    if (result.statusUpdateFlag === 1) {
      getQRcodeDataOpen.value = city.value;
      getQRcodeDataClose.value = null;
    }


    //判断如果记录成功、阀门状态更新成功、联锁相关阀门没有开启，则执行成功提醒
    if (result.recordFlag === 1 && result.statusUpdateFlag === 1 && result.valveList.length === 0) {
      uni.showToast({
        title: '打开成功！',
        icon: 'success',
        duration: 2000,
      });
      chainValveList.value = [];
      //如果联锁阀门已经有开启的，则警示提醒
    } else if (result.valveList.length >= 0) {
      uni.showToast({
        title: '联锁阀门已开启！',
        icon: 'error',
        duration: 2000,
      });
      chainValveList.value = result.valveList;
      //如果记录失败、更新阀门状态失败，则执行失败提醒
    } else if (result.recordFlag != 1 || result.statusUpdateFlag != 1) {
      uni.showToast({
        title: '记录或更新阀门状态失败！',
        icon: 'error',
        duration: 2000,
      });
      //其他未知原因错误提醒
    } else {
      uni.showToast({
        title: '未知原因失败！',
        icon: 'error',
        duration: 2000,
      });
    }

    /* temp3.then(v => {
      if (v === 2) {
        uni.showToast({
          title: '打开成功！',
          icon: 'success',
          duration: 2000,
        });
        getQRcodeDataOpen.value = city.value;
        getQRcodeDataClose.value = null;
      }
      else {
        uni.showToast({
          title: '打开失败！！',
          icon: 'error',
          duration: 2000,
        });
      }
    }) */
  } catch (error) {
    console.error('打开阀门时出错:', error);
    uni.showToast({
      title: '打开失败！！',
      icon: 'error',
      duration: 2000,
    });
  }
};


const operationValve = async (valvePositionNumber: string, status: number, operateUser: string) => {
  const response = await http<any>({
    url: '/valve/updateValveStatus',
    method: 'POST',
    data: {
      valvePositionNumber,
      status,
      operateUser
    }
  });

  return response.data as ValveOperationResult;
};

// 扫码关闭阀
const doScanCodeClose = () => {
  wx.scanCode({
    success: async (res) => {
      getQRcodeDataClose.value = null;
      getQRcodeDataOpen.value = null;

      try {

        //关闭阀门
        const result = await operationValve(res.result, 0, userName);

        //关闭联锁提醒显示
        chainValveList.value = [];
        //如果状态更新成功，则显示关闭成功提醒
        if (result.statusUpdateFlag === 1) {
          getQRcodeDataClose.value = res.result;
          getQRcodeDataOpen.value = null
          city.value = res.result;
        }

        //乳沟如果记录成功、阀门状态更新成功，则执行成功提醒
        if (result.recordFlag === 1 && result.statusUpdateFlag === 1) {
          uni.showToast({
            title: '关闭成功！',
            icon: 'success',
            duration: 2000,
          });
        } else {
          uni.showToast({
            title: '扫码关闭失败！',
            icon: 'error',
            duration: 2000,
          });
        }

      } catch (error) {
        console.error('扫码关闭阀门时出错:', error);
        uni.showToast({
          title: '扫码关闭阀门时出错！！',
          icon: 'error',
          duration: 2000,
        });
      }


      /*  result.then(v => {
         if (v === 2) {
           uni.showToast({
             title: '关闭成功！',
             icon: 'success',
             duration: 2000,
           });
           getQRcodeDataClose.value = res.result;
           getQRcodeDataOpen.value = null
           city.value = res.result;
         } else {
           uni.showToast({
             title: '关闭失败！！',
             icon: 'error',
             duration: 2000,
           });
         }
 
       }) */
    },
    fail: (err) => {
      console.error('扫描失败', err);
      uni.showToast({
        title: '扫描失败！！',
        icon: 'error',
        duration: 2000,
      });
    }
  });
};
// 扫码打开阀
const doScanCodeOpen = () => {
  wx.scanCode({
    success: async (res) => {
      getQRcodeDataOpen.value = null;
      getQRcodeDataClose.value = null;

      try {
        // 打开阀门
        const result = await operationValve(res.result, 1, userName);

        //阀门状态更新成功，则显示
        if (result.statusUpdateFlag === 1) {
          getQRcodeDataOpen.value = res.result;
          getQRcodeDataClose.value = null;
          city.value = res.result;
        }

        //判断如果记录成功、阀门状态更新成功、联锁相关阀门没有开启，则执行成功提醒
        if (result.recordFlag === 1 && result.statusUpdateFlag === 1 && result.valveList.length === 0) {
          uni.showToast({
            title: '打开成功！',
            icon: 'success',
            duration: 2000,
          });
          chainValveList.value = [];
          //如果联锁阀门已经有开启的，则警示提醒
        } else if (result.valveList.length >= 0) {
          uni.showToast({
            title: '联锁阀门已开启！',
            icon: 'error',
            duration: 2000,
          });
          chainValveList.value = result.valveList;
          //如果记录失败、更新阀门状态失败，则执行失败提醒
        } else if (result.recordFlag != 1 || result.statusUpdateFlag != 1) {
          uni.showToast({
            title: '记录或更新阀门状态失败！',
            icon: 'error',
            duration: 2000,
          });
          //其他未知原因错误提醒
        } else {
          uni.showToast({
            title: '未知原因失败！',
            icon: 'error',
            duration: 2000,
          });
        }
      } catch (error) {
        console.error('打开阀门时出错:', error);
        uni.showToast({
          title: '打开失败！！',
          icon: 'error',
          duration: 2000,
        });
      }


      /* result.then(v => {
        if (v === 2) {
          uni.showToast({
            title: '打开成功！',
            icon: 'success',
            duration: 2000,
          });
          getQRcodeDataOpen.value = res.result;
          getQRcodeDataClose.value = null;
          city.value = res.result;
        }
        else {
          uni.showToast({
            title: '打开失败！！',
            icon: 'error',
            duration: 2000,
          });
        }

      }) */

    },
    fail: (err) => {
      console.error('扫描失败', err);
      uni.showToast({
        title: '扫描失败！！',
        icon: 'error',
        duration: 2000,
      });
    }
  });
};
</script>

<style scoped>
.setMarginTop {
  margin-top: 20px;
}

.setMarginBottom {
  margin-bottom: 45px;
}

.page-body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 20vh;
  /* padding: 20rpx; */
  width: 100%;
}

.btn-area {
  text-align: center;
  width: 100%;
}

.button-sp-area {
  display: flex;
  align-items: center;
  width: 100%;
  flex-direction: row;
  justify-content: space-evenly;
}

.close-valve,
button {
  margin: 20rpx 0;
}

.text {
  color: #f00;
  font-size: large;
  font-weight: 700;
}

.view {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.example-body {
  padding: 12px;
  background-color: #FFFFFF;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.placeholder {
  width: 100%;
  height: 70vh;
  /* 根据需要调整高度 */
}

.combox {
  margin-top: 20rpx;
  width: 100px;
}
</style>